import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import MyOrder from '@/views/myorder'
import ProDetail from '@/views/prodetail'
import Pay from '@/views/pay'
import Search from '@/views/search'
import User from '@/views/layout/user'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import store from '@/store'
import SearchList from '@/views/search/list.vue'
import AddressList from '@/views/address'
import AddAddress from '@/views/address/addAddress.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        { path: '/user', component: User },
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart }
      ]
    },
    { path: '/myorder', component: MyOrder },
    // 动态路由传参，确认将来是哪个商品，路由参数中携带id
    { path: '/prodetail/:id', component: ProDetail },
    { path: '/pay', component: Pay },
    { path: '/search', component: Search },
    { path: '/searchlist/', component: SearchList },
    { path: '/addresslist/', component: AddressList },
    { path: '/addAddress', component: AddAddress }
  ]
})

// 定义一个数组，专门存放需要权限访问的页面路径
const authUrls = ['/pay', '/myorder']

router.beforeEach((to, from, next) => {
  // 1.to往哪里去，到哪里去的路由信息对象
  // 2.from从哪里来，从哪里来的路由信息对象
  // 3.next()是否放行
  //   如果next()调用，就是放行
  //   next(路径)，拦截到某个路径页面

  // 判断to.path是否时权限页面，不是直接放行
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  // 是权限页面，判断是否有token值，有直接放行，没有跳转至login
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
